package code.whmmm.util.simple.serialize;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * <p><b>
 * jdk(java)序列化 工具类,无需实例化
 * </b></p>
 * <br/>
 * 创建时间: 9/10/2019 9:14 AM
 *
 * @author Zero
 */
public class JdkSerializeUtil {

    /**
     * static 方法，无需实例化
     */
    private JdkSerializeUtil() {

    }

    private static Logger log = LoggerFactory.getLogger(JdkSerializeUtil.class);

    /**
     * 序列化
     *
     * @param object 要序列化的对象
     * @return 字节数组
     */
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        byte[] bytes = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            bytes = baos.toByteArray();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bytes;
    }

    /**
     * 反序列化
     *
     * @param bytes 字节数组
     * @return 对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T unserialize(byte[] bytes, Class<T> tClass) {
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        T t = null;
        try {
            // 反序列化
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);
            t = (T) ois.readObject();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {

            try {
                if (ois != null) {
                    ois.close();
                }

                if (bais != null) {
                    bais.close();
                }
            } catch (IOException ignored) {

            }
        }
        return t;
    }
}